package com.school.manager.utils;

import java.lang.reflect.Field;
import java.util.List;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.manager.annotations.Like;
import com.school.manager.annotations.OrderBy;
import com.school.manager.entity.po.BasePo;
import com.school.manager.entity.vo.BaseVo;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;

/**
 * description：分页工具 date：2021/10/138:59 下午
 */

public class PageUtil {

	private PageUtil() {
	}

	/**
	 * 构建query
	 *
	 * @param basePo
	 * @return
	 */
	public static <T> QueryWrapper<T> buildQueryWrapper(BasePo basePo, Class<T> clazz) {
		QueryWrapper<T> queryWrapper = new QueryWrapper<>();
		if (ObjectUtil.isEmpty(basePo)) {
			return queryWrapper;
		}
		Field[] fields = ReflectUtil.getFields(clazz);
		// 排序锁 （有多个排序时只根据第一个字段排序）
		boolean orderLock = true;
		// 设置查询条件
		for (Field field : fields) {
			Object fieldVal = ReflectUtil.getFieldValue(basePo, field.getName());
			String fieldName = field.getName();
			if (ObjectUtil.isNotEmpty(fieldVal) && !"serialVersionUID".equals(fieldName)) {
				Like like = field.getAnnotation(Like.class);
				if (like != null && like.pre()) {
					queryWrapper.likeLeft(like.value(), fieldVal);
					break;
				} else if (like != null && like.aft()) {
					queryWrapper.likeRight(like.value(), fieldVal);
					break;
				} else if (like != null) {
					queryWrapper.like(like.value(), fieldVal);
					break;
				}
				TableField annotation = field.getAnnotation(TableField.class);
				queryWrapper.eq(annotation.value(), fieldVal);
				OrderBy order = field.getAnnotation(OrderBy.class);
				if (order != null && orderLock) {
					queryWrapper.orderByAsc(annotation.value());
					orderLock = false;
				}
			}
		}
		return queryWrapper;
	}

	/**
	 * 创建分页结果
	 *
	 * @param page
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <K, T extends BaseVo> Page<T> buildPage(Page<K> page, Class<T> clazz) {
		List<T> target = ConvertUtil.convertList(page.getRecords(), clazz);
		Page<T> result = new Page<>();
		result.setRecords(target);
		result.setCurrent(page.getCurrent());
		result.setSize(page.getSize());
		result.setTotal(page.getTotal());
		return result;
	}
}
